define(
	[
		'require',
		'./detail_ctrl'
	],
	function(require) {
		var Controller = Ember.Controller.extend({
			needs: ["businessDetail"],

			today: Ember.computed(function() {
				return APM.util.formatDate(new Date(new Date() - timeD_value), "D");
			}),

			modelChange: Ember.observer("model", function() {
				if (!this.get("model")) {
					return;
				}
				this._requirePerformances();
			}),

			isTradingMode: false,

			init: function() {
				if (!$.cookie("isThreshold")) {
					overviewOrCenterSwitch = "system";
				}
				if (this.get("auth.user").role == 1) {
					this.set("administrators", true);
				}
			},

			/*
				向服务端请求业务系统列表
			*/
			requireApplications: function() {
				return this.store.ajax("GET", "applications")
					.then(function(response) {
						var applications = Ember.A(response.applications);
						applications.forEach(function(app) {
							app.viewName = "appSequenceView_" + app.id;
						});
						return applications;
					});
			},

			performances: Ember.A(),

			requirePerformances: function(applications, overview, oStartDate, oEndDate) {
				var ctrl = this,
					overallPerformances = ctrl.get('performances');;
				var appIds = applications.map(function(app) {
					return app.id;
				});
				if (appIds.length == 0) {
					return Ember.RSVP.reject("没有业务系统");
				}

				var startDate, endDate;

				endDate = new Date(new Date() - timeD_value);
				endDate.setMinutes(endDate.getMinutes() - 1);
				endDate.setSeconds(0);
				endDate.setMilliseconds(0);
				startDate = new Date(+endDate)
				startDate.setHours(startDate.getHours() - 1);

				//开发调试模式参数
				if (isLocalDebugModel) {
					endDate = new Date(2014, 9, 1, 12, 0, 0);
					startDate = new Date(+endDate)
					startDate.setHours(startDate.getHours() - 1);
				}

				if (overview) {
					startDate = oStartDate;
					endDate = oEndDate;
				}
				return this.store.ajax("GET", "performances", {
						appIds: appIds.join(),
						startDate: +startDate,
						endDate: +endDate,
					})
					.then(function(response) {
						applications.forEach(function(app) {
							response[app.id] = ctrl.performancesCompletion(response[app.id], startDate, endDate);
							overallPerformances.pushObject(response[app.id]);

							Ember.set(app, "performances", response[app.id]);

						});
						return response;
					});
			},

			_requirePerformances: function() {
				var ctrl = this;
				var applications = this.get("model");
				return this.requirePerformances(applications)
					.then(function() {
						ctrl._setAppXAxisTime();
					});
			},

			startRealTimeMode: function() {
				if (this.timeTicket) {
					return;
				}

				_requireData(this);

				function _requireData(ctrl) {
					var interval = 60000;
					if (isLocalDebugModel) {
						interval = 6000;
					}
					ctrl.timeTicket = setTimeout(function() {
						ctrl._requirePerformances()
							.then(function(response) {
								_requireData(ctrl);
							});
					}, interval);
				}
			},

			stopRealTimeMode: function() {
				clearTimeout(this.timeTicket);
				this.timeTicket = null;
			},

			/*
				自动智能补全性能数据以填充图标, 按每分钟一条数据
				@param {array} performances 性能数组
				@param {nunber} startDate 补全后的目标长度
				@param {date} endDate 结束时间
				@param {string} dateType 时间显示类型{1.今天，2.昨天，3.上周}
			*/
			performancesCompletion: function(performances, startDate, endDate, dateType, minites15) {
				startDate = new Date(+startDate),
					endDate = new Date(+endDate);
				if (!startDate && !endDate) {
					Ember.assert("startDate, 或者endDate参数不是时间");
					return;
				}

				performances = performances || [];

				startDate.setSeconds(0);
				startDate.setMilliseconds(0);
				endDate.setSeconds(0);
				endDate.setMilliseconds(0);

				var performancesMap = {};
				for (var i = performances.length - 1; i >= 0; i--) {
					performancesMap[performances[i].timestamp] = performances[i];
					if (dateType) {
						performances[i].timestampType = dateType;
					}
				}

				var timestamp = +startDate,
					newPerformances = [];

				if (minites15) {
					for (; timestamp < +endDate; timestamp += 900000) {
						if (!performancesMap[timestamp]) {
							newPerformances.push({
								"timestamp": timestamp
							});
						} else {
							newPerformances.push(performancesMap[timestamp]);
						}
					}
				} else {
					for (; timestamp < +endDate; timestamp += 60000) {
						if (!performancesMap[timestamp]) {
							newPerformances.push({
								"timestamp": timestamp
							});
						} else {
							newPerformances.push(performancesMap[timestamp]);
						}
					}
				}

				return Ember.A(newPerformances);
			},

			_setAppXAxisTime: function(apps) {
				var applications = Ember.A(apps || this.get("model"));
				var set = Ember.set,
					formatDate = APM.util.formatDate;

				applications.forEach(function(app) {
					var performances = app.performances;
					set(app, "startXAxisTime", formatDate(performances[0].timestamp, "t"));
					set(app, "endXAxisTime", formatDate(performances[performances.length - 1].timestamp, "t"));
				});
			},

			dialogButtons: {
				ok: {
					text: "确定",
					"class": "btn btn-primary",
					click: function() {
						var ctrl = this.get("controller");

						switch (this.id) {
							case "businessApplicationAdd":
								ctrl.addApplication();
								break;
							case "businessApplicationEdit":
								ctrl.updateApplication();
								break;
						}
					}
				},
				cancel: {
					text: "取消",
					"class": "btn",
					click: function() {
						this.closeDialog();
					}
				}
			},

			addApplication: function() {
				var ctrl = this,
					model = ctrl.get("applicationModel");

				if (!this.validateAppForm()) {
					return;
				}

				ctrl.postApplication(model)
					.then(function() {
						Broada.getView("businessApplicationAdd").closeDialog();
						return ctrl.requireApplications();
					})
					.then(function(applications) {
						ctrl.set("model", applications);
					});
			},

			updateApplication: function() {
				var ctrl = this,
					model = ctrl.get("applicationModel"),
					app = ctrl.get('curEditApp'),
					name = $.trim(model.name);

				if (!this.validateAppForm()) {
					return;
				}

				ctrl.postApplication(model)
					.then(function() {
						Ember.set(app, "name", name);
						Broada.getView("businessApplicationEdit").closeDialog();
					});
			},

			postApplication: function(model) {
				return this.store.ajax("POST", "applications", model);
			},

			deleteApplication: function(app) {
				return this.store.ajax("DELETE", "applications/" + app.id);
			},

			validateAppForm: function() {
				var ctrl = this,
					model = ctrl.get("applicationModel"),
					applications = ctrl.get('model'),
					name = $.trim(model.name);

				if (!name) {
					ctrl.set("businessAddformTip", "业务系统名称不能为空！");
					return false;
				}

				var tmpApp = applications.filterBy('name', name);
				if (tmpApp[0] && (!model.id || tmpApp.length != Ember.A(tmpApp).filterBy('id', model.id).length)) {
					ctrl.set("businessAddformTip", "业务系统名称不能重复！");
					return false;
				}

				ctrl.set("businessAddformTip", null);
				return true;
			},

			actions: {
				startAddApplication: function() {
					this.set('applicationModel', {});
					this.set("businessAddformTip", null);
					Broada.getView("businessApplicationAdd").openDialog();
				},

				startEditApplication: function(app) {
					this.set('applicationModel', {
						name: app.name,
						id: app.id
					});
					this.set('curEditApp', app);
					this.set("businessAddformTip", null)
					Broada.getView("businessApplicationEdit").openDialog();
				},

				addApplication: function() {
					this.addApplication();
				},

				updateApplication: function() {
					this.updateApplication();
				},

				deleteApplication: function(app) {
					var ctrl = this;
					confirmDialog('确定要删除业务系统么？')
						.then(function() {
							return ctrl.deleteApplication(app)
						})
						.then(function() {
							ctrl.get("model").removeObject(app);
						});
				},

				moveUpApplication: function(app) {
					var model = this.get('model'),
						prev = model[model.indexOf(app) - 1];

					this.send('swapBusinessApplication', prev.id, app.id);
				},

				moveDownApplication: function(app) {
					var model = this.get('model'),
						next = model[model.indexOf(app) + 1];

					this.send('swapBusinessApplication', app.id, next.id);
				},

				swapBusinessApplication: function(id1, id2) {
					var ctrl = this;
					this.store.ajax("POST", "applications/changeorder", {
						id1: id1,
						id2: id2
					}).then(function() {

						ctrl.requireApplications()
							.then(function(applications) {
								ctrl.set("model", applications);
							});
					})
				},

				sequenceItemClick: function(args, view) {
					var ctrl = this;
					switch (view.displayMode) {
						case "detail":
							this.set("timePoint", args.timestamp);
							setTimeout(function() {
								overviewOrCenterSwitch = "system";
								$.cookie("isThreshold", "", -1);
								ctrl.transitionToRoute("business.detail.gauge", view.appData.id, {
									queryParams: {
										startTime: args.timestamp,
										pinTimePoint: true
									}
								});
							}, 10);
							break;
					}
				}
			}
		});

		APM.BusinessCenterController = Controller;

		return Controller;
	}
);